import cv2  
import os  
import numpy as np
  
# 图片文件夹路径  
image_folder = r'F:\SY_data_set\化工盒子\image_ori'  
# 视频保存路径  
video_name = '111.mp4'  
# 视频帧率  
fps = 25.0  
# 图片尺寸（如果所有图片尺寸一致，可以随机读取一张来获取）  
frame_size = (1920, 1080)  # 根据你的图片尺寸调整  
  
# 获取图片文件夹中所有图片的文件名  
image_files = [f for f in os.listdir(image_folder) if f.endswith('.jpg') or f.endswith('.png') or f.endswith('.jpeg')]  
# 对图片文件名进行排序，确保按照正确的顺序合成视频  
image_files.sort()  
  
# 创建VideoWriter对象  
# fourcc = cv2.VideoWriter_fourcc(
#                 'm', 'p', '4', 'v')  # opencv3.0
                

# fourcc = cv2.VideoWriter_fourcc(*'X264')
fourcc = cv2.VideoWriter_fourcc(*'X264')
# avc1
# fourcc = cv2.VideoWriter_fourcc(*'XVID')  # 使用XVID编码  
out = cv2.VideoWriter(video_name, fourcc, fps, frame_size)  
  
# 遍历图片并写入视频  
for image_file in image_files:  
    image_path = os.path.join(image_folder, image_file)  
    frame = cv2.imdecode(np.fromfile(image_path,dtype=np.uint8),cv2.IMREAD_COLOR)  
    # print(frame.shape)
    frame = cv2.resize(frame, frame_size, interpolation=cv2.INTER_LINEAR)
    out.write(frame)  # 写入帧  
  
# 释放VideoWriter对象  
out.release()  
print(f"Video {video_name} created successfully!")